import requests
import json
from typing import Dict, Any, List


def get_weibo_trending() -> List[Dict[str, Any]]:
    """
    获取微博实时热搜榜数据
    
    返回微博热搜榜前20条数据，包含时事热点、社会现象、娱乐新闻、
    明星动态及网络热议话题的实时热门中文资讯。

    """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'https://weibo.com/'
        }
        
        response = requests.get('https://weibo.com/ajax/side/hotSearch', headers=headers)
        if response.status_code == 200:
            data = response.json()
            # 提取热搜数据并标准化格式
            if data.get('data') and data['data'].get('realtime'):
                trending_list = []
                # 返回前10条数据，而不是只有1条
                for i, item in enumerate(data['data']['realtime'][:5]):
                    trending_list.append({
                        'index': i + 1,
                        'title': item.get('word', ''),
                        'url': f"https://s.weibo.com/weibo?q={item.get('word', '')}",
                        'hot': item.get('num', 0),
                        'desc': item.get('note', '')  # 添加描述字段，提高文案质量
                    })
                return trending_list
        return []
        
    except Exception as e:
        # 添加更详细的错误处理和日志
        print(f"获取微博热搜失败: {e}")
        # 返回一个备用热点数据，确保系统可以继续运行
        return [
            {
                'index': 1,
                'title': '热点获取失败，使用备用数据',
                'url': 'https://s.weibo.com/top/summary',
                'hot': 999999,
                'desc': '当前热点数据获取遇到问题，请稍后再试。'
            }
        ]

"""
def get_baidu_trending() -> List[Dict[str, Any]]:
    """ """
    获取百度实时热搜榜数据
    
    返回百度热搜榜数据，包含时事热点、社会现象、娱乐新闻等实时热门中文资讯。
    """ """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://top.baidu.com/',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Cache-Control': 'no-cache',
        }
        
        # 使用更稳定的百度热搜API
        response = requests.get('https://top.baidu.com/board?platform=pc&tab=realtime', headers=headers)
        
        # 百度热搜页面是HTML格式，需要解析
        if response.status_code == 200:
            # 使用正则表达式提取热搜数据
            import re
            pattern = r'"rawUrl":"[^"]*","word":"([^"]*)"'
            matches = re.findall(pattern, response.text)
            
            # 构建标准化热搜列表
            trending_list = []
            for i, word in enumerate(matches[:20]):
                trending_list.append({
                    'index': i + 1,
                    'title': word,
                    'url': f'https://www.baidu.com/s?wd={word}',
                    'hot': 0  # 百度热搜热度信息不易获取，设为0
                })
            
            return trending_list
        
        return []
        
    except Exception as e:
        print(f"获取百度热搜失败: {e}")
        return []
"""
"""
def get_zhihu_trending() -> List[Dict[str, Any]]:
    """"""
    获取知乎实时热搜榜数据
    
    返回知乎热搜榜数据，包含时事热点、社会现象、娱乐新闻等实时热门中文资讯。
    """"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://www.zhihu.com/hot',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Cache-Control': 'no-cache',
            'x-requested-with': 'fetch',
            'x-zse-96': '2.0_',  # 可能需要动态生成
        }
        
        # 使用知乎热搜API
        response = requests.get('https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total?limit=50', headers=headers)
        
        if response.status_code == 200:
            data = response.json()
            # 提取热搜数据并标准化格式
            if data.get('data'):
                trending_list = []
            for i, item in enumerate(data['data'][:5]):
                    target = item.get('target', {})
                    trending_list.append({
                        'index': i + 1,
                        'title': target.get('title', ''),
                        'url': target.get('url', f'https://www.zhihu.com/search?type=content&q={target.get("title", "")}'),
                        'hot': item.get('detail_text', '')  # 知乎热度信息在detail_text中
                    })
                return trending_list
        
        # 如果API失败，尝试备用方案
        backup_response = requests.get('https://www.zhihu.com/hot', headers=headers)
        if backup_response.status_code == 200:
            import re
            # 从HTML中提取热搜数据
            pattern = r'HotList-pageCard.*?HotItem-title.*?>([^<]*)</div>'
            matches = re.findall(pattern, backup_response.text)
            
            trending_list = []
            for i, title in enumerate(matches[:20]):
                trending_list.append({
                    'index': i + 1,
                    'title': title.strip(),
                    'url': f'https://www.zhihu.com/search?type=content&q={title}',
                    'hot': ''  # 备用方案无法获取热度信息
                })
            
            return trending_list
        
        return []
        
    except Exception as e:
        print(f"获取知乎热搜失败: {e}")
        return []

"""
def get_toutiao_trending() -> List[Dict[str, Any]]:
    """
    获取头条实时热搜榜数据
    
    返回头条热搜榜数据，包含时事热点、社会现象、娱乐新闻等实时热门中文资讯。
    """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Referer': 'https://www.toutiao.com/'
        }
        
        response = requests.get('https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc', headers=headers)
        data = response.json()
        
        # 提取热搜数据并标准化格式
        if data.get('data'):
            trending_list = []
            # 返回前5条数据
            for i, item in enumerate(data['data'][:5]):
                trending_list.append({
                    'index': i + 1,
                    'title': item.get('Title', ''),
                    'url': item.get('Url', f'https://www.toutiao.com/search/?keyword={item.get("Title", "")}'),
                    'hot': item.get('HotValue', 0),  # 头条热度信息在HotValue中
                    'desc': item.get('Abstract', '')  # 添加摘要字段，提高文案质量
                })
            return trending_list
        
        return []
        
    except Exception as e:
        # 添加更详细的错误处理和日志
        print(f"获取头条热搜失败: {e}")
        # 返回一个备用热点数据，确保系统可以继续运行
        return [
            {
                'index': 1,
                'title': '热点获取失败，使用备用数据',
                'url': 'https://www.toutiao.com/hot-event/hot-board/',
                'hot': 999999,
                'desc': '当前热点数据获取遇到问题，请稍后再试。'
            }
        ]


def get_douyin_trending() -> List[Dict[str, Any]]:
    """
    获取抖音实时热搜榜数据
    
    返回抖音热搜榜数据，包含时事热点、社会现象、娱乐新闻等实时热门中文资讯。
    """
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Referer': 'https://www.douyin.com/',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Cache-Control': 'no-cache',
            # 抖音需要模拟移动端User-Agent
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1'
        }
        
        # 使用抖音移动端热搜API
        response = requests.get('https://www.douyin.com/aweme/v1/web/hot/search/list/', headers=headers)

        if response.status_code == 200:
            data = response.json()
            # 提取热搜数据并标准化格式
            if data.get('data') and data['data'].get('word_list'):
                trending_list = []
                # 返回前10条数据，而不是只有1条
                for i, item in enumerate(data['data']['word_list'][:5]):
                    trending_list.append({
                        'index': i + 1,
                        'title': item.get('word', ''),
                        'url': f'https://www.douyin.com/search/{item.get("word", "")}',
                        'hot': item.get('hot_value', 0),  # 抖音热度信息在hot_value中
                        'desc': item.get('content', '')  # 添加内容描述字段，提高文案质量
                    })
                return trending_list
        
        return []
        
    except Exception as e:
        # 添加更详细的错误处理和日志
        print(f"获取抖音热搜失败: {e}")
        # 返回一个备用热点数据，确保系统可以继续运行
        return [
            {
                'index': 1,
                'title': '热点获取失败，使用备用数据',
                'url': 'https://www.douyin.com/search/',
                'hot': 999999,
                'desc': '当前热点数据获取遇到问题，请稍后再试。'
            }
        ]

"""
def test_all_trending_apis():
    """ """
    测试所有热搜榜API
    """ """
    print("=" * 50)
    print("开始测试热搜榜API")
    print("=" * 50)
    
    # 测试微博热搜
    print("\n1. 测试微博热搜:")
    weibo_data = get_weibo_trending()
    if weibo_data:
        print(f"微博热搜获取成功，数据条数: {len(weibo_data)}")
        # 打印前5条热搜
        for i, item in enumerate(weibo_data[:5]):
            print(f"  {i+1}. {item.get('title', '未知')} (热度: {item.get('hot', '未知')})(链接: {item.get('url', '未知')})")
    else:
        print("微博热搜获取失败")
    
    # 测试百度热搜
    print("\n2. 测试百度热搜:")
    baidu_data = get_baidu_trending()
    if baidu_data:
        print(f"百度热搜获取成功，数据条数: {len(baidu_data)}")
        # 打印前5条热搜
        for i, item in enumerate(baidu_data[:5]):
            print(f"  {i+1}. {item.get('title', '未知')} (热度: {item.get('hot', '未知')})(链接: {item.get('url', '未知')})")
    else:
        print("百度热搜获取失败")
    
    # 测试知乎热搜
    print("\n3. 测试知乎热搜:")
    zhihu_data = get_zhihu_trending()
    if zhihu_data:
        print(f"知乎热搜获取成功，数据条数: {len(zhihu_data)}")
        # 打印前5条热搜
        for i, item in enumerate(zhihu_data[:5]):
            print(f"  {i+1}. {item.get('title', '未知')} (热度: {item.get('hot', '未知')})(链接: {item.get('url', '未知')})")
    else:
        print("知乎热搜获取失败")
    
    # 测试头条热搜
    print("\n4. 测试头条热搜:")
    toutiao_data = get_toutiao_trending()
    if toutiao_data:
        print(f"头条热搜获取成功，数据条数: {len(toutiao_data)}")
        # 打印前5条热搜
        for i, item in enumerate(toutiao_data[:5]):
            print(f"  {i+1}. {item.get('title', '未知')} (热度: {item.get('hot', '未知')})(链接: {item.get('url', '未知')})")
    else:
        print("头条热搜获取失败")
    
    # 测试抖音热搜
    print("\n5. 测试抖音热搜:")
    douyin_data = get_douyin_trending()
    if douyin_data:
        print(f"抖音热搜获取成功，数据条数: {len(douyin_data)}")
        # 打印前5条热搜
        for i, item in enumerate(douyin_data[:5]):
            print(f"  {i+1}. {item.get('title', '未知')} (热度: {item.get('hot', '未知')})(链接: {item.get('url', '未知')})")
    else:
        print("抖音热搜获取失败")
    
    print("\n" + "=" * 50)
    print("测试完成")
    print("=" * 50)

"""
def test_specific_platform(platform: str):
    """
    测试特定平台的热搜榜
    
    Args:
        platform: 平台名称 ('weibo', 'baidu', 'zhihu', 'toutiao', 'douyin')
    """
    platform_functions = {
        'weibo': get_weibo_trending,
        #'baidu': get_baidu_trending,
        #'zhihu': get_zhihu_trending,
        'toutiao': get_toutiao_trending,
        'douyin': get_douyin_trending
    }
    
    if platform not in platform_functions:
        print(f"未知平台: {platform}")
        return
    
    print(f"测试 {platform} 热搜榜:")
    data = platform_functions[platform]()
    
    if data:
        print(f"获取成功，数据类型: {type(data)}")
        print(f"数据预览: {str(data)[:200]}...")
    else:
        print("获取失败")


if __name__ == "__main__":
    # 运行完整测试
    #test_all_trending_apis()
    
    # 也可以单独测试某个平台
    test_specific_platform('baidu')
    test_specific_platform('zhihu')
    test_specific_platform('toutiao')
    test_specific_platform('douyin')
